package com.spzx.rabbit.service;

import com.alibaba.fastjson2.JSON;
import com.spzx.rabbit.entity.GuiguCorrelationData;
import org.springframework.amqp.AmqpException;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessagePostProcessor;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class RabbitService {

    @Autowired
    RabbitTemplate rabbitTemplate;

    @Autowired
    RedisTemplate redisTemplate;

    public boolean sendDealyMessage(String exchange, String routingKey, Object message, int delayTime) {
        //1.创建自定义相关消息对象-包含业务数据本身，交换器名称，路由键，队列类型，延迟时间,重试次数
        GuiguCorrelationData correlationData = new GuiguCorrelationData();
        String uuid = "mq:" + UUID.randomUUID().toString().replaceAll("-", "").substring(0, 8);
        correlationData.setId(uuid);
        correlationData.setMessage(message);
        correlationData.setExchange(exchange);
        correlationData.setRoutingKey(routingKey);
        correlationData.setDelay(true);// 设置延迟标志位
        correlationData.setDelayTime(delayTime);

        rabbitTemplate.convertAndSend(exchange, routingKey, message, new MessagePostProcessor() {
            @Override
            public Message postProcessMessage(Message message) {
                message.getMessageProperties().setDelay(1000 * delayTime);
                return message;
            }
        }, correlationData);

        redisTemplate.opsForValue().set(uuid, JSON.toJSONString(correlationData), 10, TimeUnit.MINUTES);
        return true;
    }

    public void sendMessage(String exchange, String routing, Object message) {
        GuiguCorrelationData guiguCorrelationData = new GuiguCorrelationData();
        String guiguCorrelationDataId = UUID.randomUUID().toString().replace("-", "").substring(0, 8);
        guiguCorrelationData.setId(guiguCorrelationDataId);
        guiguCorrelationData.setRetryCount(3);
        guiguCorrelationData.setMessage(message);
        guiguCorrelationData.setExchange(exchange);
        guiguCorrelationData.setRoutingKey(routing);
        guiguCorrelationData.setDelay(false);
        // 保存redis的副本
        redisTemplate.opsForValue().set(guiguCorrelationDataId, JSON.toJSONString(guiguCorrelationData), 10, TimeUnit.MINUTES);
        rabbitTemplate.convertAndSend(exchange, routing, message, guiguCorrelationData);
    }

}
